package com.ruoyi.consumer.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.PaymentStatusEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.consumer.domain.TPaymentHy;
import com.ruoyi.consumer.domain.UserRoomRel;
import com.ruoyi.consumer.domain.VPaymentHy;
import com.ruoyi.consumer.domain.query.TPaymentHyQuery;
import com.ruoyi.consumer.domain.query.VPaymentHyQuery;
import com.ruoyi.consumer.mapper.PaymentHyMapper;
import com.ruoyi.consumer.mapper.UserRoomRelMapper;
import com.ruoyi.consumer.service.IUserRoomRelService;
import com.ruoyi.consumer.service.SysFeeHyService;
import com.ruoyi.consumer.util.WechatPayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户房产绑定关系Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-22
 */
@Service
public class UserRoomRelServiceImpl implements IUserRoomRelService {

    @Autowired
    private UserRoomRelMapper userRoomRelMapper;
    @Autowired
    private PaymentHyMapper paymentHyMapper;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysFeeHyService sysFeeHyService;

    /**
     * 查询用户房产绑定关系
     *
     * @param id 用户房产绑定关系主键
     * @return 用户房产绑定关系
     */
    @Override
    public UserRoomRel selectUserRoomRelById(Long id) {
        return userRoomRelMapper.selectUserRoomRelById(id);
    }


    /**
     * 内管列表查询
     * @author lisongtao
     * @date 2023/11/7 23:47
     * @param userRoomRel
     * @return
     */
    @Override
    public List<UserRoomRel> selectUserRoomRelListInner(UserRoomRel userRoomRel) {
        return userRoomRelMapper.selectUserRoomRelList(userRoomRel);
    }

    /**
     * 查询用户房产绑定关系列表
     *
     * @param userRoomRel 用户房产绑定关系
     * @return 用户房产绑定关系
     */
    @Override
    public List<UserRoomRel> selectUserRoomRelList(UserRoomRel userRoomRel) {
        String paymentYear = sysFeeHyService.getPaymentYear();
        List<UserRoomRel> userRoomRels = userRoomRelMapper.selectUserRoomRelList(userRoomRel);
        if (CollUtil.isNotEmpty(userRoomRels)) {
            List<String> roomIds = userRoomRels.stream().map(UserRoomRel::getRoomId).filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
            if (CollUtil.isEmpty(roomIds)) {
                return new ArrayList<>();
            }
            VPaymentHyQuery vPaymentHyQuery = new VPaymentHyQuery();
            vPaymentHyQuery.setRoomIds(roomIds);
            vPaymentHyQuery.setYear(paymentYear);
            List<VPaymentHy> vPaymentHyLists = paymentHyMapper.selectVPaymentHyByParam(vPaymentHyQuery);
            for (UserRoomRel roomRel : userRoomRels) {
                VPaymentHy vPaymentHy1 = vPaymentHyLists.stream().filter(vPaymentHy -> vPaymentHy.getRoomId().equals(roomRel.getRoomId())).findFirst().orElse(null);
                roomRel.setYear(paymentYear);
                if (vPaymentHy1 != null) {
                    // 先将记录设置为未缴费，根据查询的状态设置真实的缴费状态
                    roomRel.setPaymentStatus(PaymentStatusEnum.INABILITY_TO_PAY.getCode());
                    roomRel.setErrorPrompt("缴费状态异常，请去营业厅办理办理！");

                    roomRel.setHmd(vPaymentHy1.getHmd());
                    roomRel.setFyzt(vPaymentHy1.getFyzt());
                    roomRel.setSfdb(vPaymentHy1.getSfdb());
                    roomRel.setChecked(vPaymentHy1.getChecked());
                    roomRel.setPlanId(vPaymentHy1.getPlanId());
                    roomRel.setFclx(vPaymentHy1.getFclx());
                    roomRel.setArea(vPaymentHy1.getArea());
                    roomRel.setPrice(vPaymentHy1.getPrice());
                    roomRel.setPayableAmount(vPaymentHy1.getPayableAmount());
                    // 判断roomId字段和供热编号字段，是否与绑定是相同，不相同认定为，绑定关系取消，要提示报错
                    String heatNumber = roomRel.getHeatNumber();
                    String cardNo = vPaymentHy1.getCardNo();
                    String planId = vPaymentHy1.getPlanId();
                    if (StringUtils.isBlank(heatNumber) || StringUtils.isBlank(cardNo) || !heatNumber.equals(cardNo)) {
                        roomRel.setPaymentStatus(PaymentStatusEnum.CARD_ERROR.getCode());
                        roomRel.setErrorPrompt("卡号异常，请删除关联关系！");
                        continue;
                    }

//                    显示在线支付按钮，否则提示到营业厅办理：如果hmd为黑名单，提示缴费状态异常，请去营业厅办理办理；
//                    如果fyzt为null、陈欠、未销售，提示有陈欠未处理，请去营业厅办理办理；供热中和报停可以缴费
//                    如果sfdb为是，提示低保用户不能网上缴费，请去营业厅办理办理
                    String hmd = vPaymentHy1.getHmd();
                    String fyzt = vPaymentHy1.getFyzt();
                    String sfdb = vPaymentHy1.getSfdb();
                    // 判断是否为黑名单
                    if ("黑名单".equals(hmd.trim())) {
                        roomRel.setErrorPrompt("缴费状态异常，请去营业厅办理办理！");
                        continue;
                    }
                    // 判断费用状态
                    if (!("供热中".equals(fyzt) || "报停".equals(fyzt))) {
                        roomRel.setErrorPrompt("有陈欠未处理，请去营业厅办理办理！");
                        continue;
                    }
                    // 判断是否为低保用户
                    if ("是".equals(sfdb)) {
                        roomRel.setErrorPrompt("低保用户不能网上缴费，请去营业厅办理办理！");
                        continue;
                    }
                    // 判断当前是否为支付中
                    if (redisCache.exists(StringUtils.format(WechatPayUtils.PLAN_ID_UNDER_PAY_STATUS, planId))) {
                        roomRel.setPaymentStatus(PaymentStatusEnum.UNDER_PAY.getCode());
                        roomRel.setErrorPrompt("当前缴费计划正在支付中！");
                        continue;
                    }
                    // 最终判断原数据库状态
                    String checked = vPaymentHy1.getChecked();
                    roomRel.setErrorPrompt(null);
                    if ("0".equals(checked)) {
                        roomRel.setPaymentStatus(PaymentStatusEnum.UNPAID_PAYMENT.getCode());
                    } else {
                        roomRel.setPaymentStatus(PaymentStatusEnum.PAID.getCode());
                    }
                } else {
                    // 若没有查询到缴费计划
                    roomRel.setPaymentStatus(PaymentStatusEnum.INABILITY_TO_PAY.getCode());
                    roomRel.setErrorPrompt("未查询到当前户号" + paymentYear + "年度缴费计划！");
                }
            }
        }
        return userRoomRels;
    }


    /**
     * 微信端查询支付记录
     *
     * @author lisongtao
     * @date 2023/11/2 17:29
     * @param tPaymentHyQuery
     * @return
     */
    @Override
    public List<TPaymentHy> selectPaymentRecord(TPaymentHyQuery tPaymentHyQuery) {
        String roomId = tPaymentHyQuery.getRoomId();
        if (StringUtils.isBlank(roomId)) {
            throw new ServiceException("房源编号不能为空！");
        }
        return paymentHyMapper.selectTPaymentHyByParam(tPaymentHyQuery);
    }

    /**
     * 新增用户房产绑定关系
     *
     * @param userRoomRel 用户房产绑定关系
     * @return 结果
     */
    @Override
    public int insertUserRoomRel(UserRoomRel userRoomRel) {
        userRoomRel.setCreateTime(DateUtils.getNowDate());
        return userRoomRelMapper.insertUserRoomRel(userRoomRel);
    }

    /**
     * 修改用户房产绑定关系
     *
     * @param userRoomRel 用户房产绑定关系
     * @return 结果
     */
    @Override
    public int updateUserRoomRel(UserRoomRel userRoomRel) {
        userRoomRel.setUpdateTime(DateUtils.getNowDate());
        return userRoomRelMapper.updateUserRoomRel(userRoomRel);
    }

    /**
     * 批量删除用户房产绑定关系
     *
     * @param ids 需要删除的用户房产绑定关系主键
     * @return 结果
     */
    @Override
    public int deleteUserRoomRelByIds(Long[] ids) {
        return userRoomRelMapper.deleteUserRoomRelByIds(ids);
    }

    /**
     * 删除用户房产绑定关系信息
     *
     * @param id 用户房产绑定关系主键
     * @return 结果
     */
    @Override
    public int deleteUserRoomRelById(Long id) {
        Assert.notNull(id, "绑定关系编号不能为空！");
        return userRoomRelMapper.deleteUserRoomRelById(id);
    }


    /**
     * 获取缴费年度
     */
//    @Override
//    public String getPaymentYear() {
//
//        // 此处获取的为 月-日
////        String configValue = sysConfigService.selectConfigByKey(WechatPayUtils.WECHAT_PAYMENT_YEAR);
////        if (StringUtils.isBlank(configValue)) {
////            throw new ServiceException("缴费年度设置错误，无法查询！");
////        }
////        // 拼接获得年度信息
////        String year = DateUtils.dateTimeNow(DateUtils.YYYY);
////        String criticalStringValue = year + configValue + " 00:00:00";
////        // 拼接后的日期为  2024-5-1
////        Date criticalDate = DateUtils.parseDate(criticalStringValue);
////        Date nowDate = new Date();
////        String paymentYear;
////        if (nowDate.before(criticalDate)) {
////            // 供热年度为上一年度
////            Date date = DateUtils.addYears(new Date(), -1);
////            paymentYear = DateUtils.parseDateToStr(DateUtils.YYYY, date);
////        } else {
////            // 供热年度为当前年度
////            paymentYear = year;
////        }
//
//        return null;
//    }

}
